import { autoScrollInContainer, scrollToElement } from '../../utils/scroll-helper.js';
import { selectors, groupConfig } from './config.js';
import { findAllGroupContainers, findTitle, getElementIdentifier } from './group-helper.js';
import TabManager from './tab-manager.js';

// 检查元素是否为白色圆角容器
function isWhiteCardContainer(element) {
  if (!element || element.tagName.toLowerCase() !== 'div') {
    return false;
  }
  
  const style = element.style;
  const computedStyle = window.getComputedStyle(element);
  
  // 检查背景色是否为白色或白色渐变
  const background = style.background || computedStyle.background;
  const backgroundColor = style.backgroundColor || computedStyle.backgroundColor;
  const isWhite = 
    // 纯白色背景
    groupConfig.container.backgroundColor.some(color => 
      backgroundColor === color
    ) ||
    // 白色渐变背景
    (background && groupConfig.container.backgroundGradient.some(gradient => 
      background.includes(gradient)
    ));
  
  // 检查是否有圆角
  const borderRadius = style.borderRadius || computedStyle.borderRadius;
  const hasBorderRadius = !groupConfig.container.borderRadius.not.includes(borderRadius);
  
  // 检查元素本身是否是卡片
  const isCardElement = groupConfig.card.classes.some(className => 
    element.classList.contains(className.replace('.', ''))
  );
  
  return {
    isWhite,
    hasBorderRadius,
    isCardElement
  };
}

// 检查元素是否是卡片容器（而不是分组容器）
function isCardContainer(element) {
  // 检查元素本身是否是卡片
  if (groupConfig.card.classes.some(className => 
    element.classList.contains(className.replace('.', ''))
  )) {
    return true;
  }
  
  // 检查是否只包含卡片元素
  const children = Array.from(element.children);
  if (children.length === 0) return false;
  
  // 如果所有子元素都是卡片，则认为是卡片容器
  return children.every(child => 
    groupConfig.card.classes.some(className => 
      child.classList.contains(className.replace('.', ''))
    )
  );
}

// 检查标签是否在分组内
function isTabInGroup(tabElement, groupContainer) {
  const tabRect = tabElement.getBoundingClientRect();
  const groupRect = groupContainer.getBoundingClientRect();
  
  return (
    tabRect.top >= groupRect.top &&
    tabRect.bottom <= groupRect.bottom
  );
}

// 处理初始分组
async function processInitialGroups(root, extractCards) {
  const groups = [];
  const { containers: initialGroupContainers, reasons: initialReasons } = findAllGroupContainers(root);
  console.log(`找到 ${initialGroupContainers.length} 个分组容器:`, 
    initialGroupContainers.map(c => getElementIdentifier(c)));

  // 创建标签页管理器来获取组外标签组位置
  const tabManager = new TabManager();
  await tabManager.initialize();
  const outerTabGroups = tabManager.getOuterTabGroups();
  
  // 获取第一个组外标签组的位置
  let firstOuterTabPosition = Infinity;
  if (outerTabGroups.length > 0) {
    const firstOuterTab = outerTabGroups[0];
    const firstOuterTabRect = firstOuterTab.element.getBoundingClientRect();
    firstOuterTabPosition = firstOuterTabRect.top;
  }

  // 过滤并处理分组
  for (const [index, groupContainer] of initialGroupContainers.entries()) {
    // 检查分组是否在第一个组外标签组之前
    const groupRect = groupContainer.getBoundingClientRect();
    if (groupRect.top >= firstOuterTabPosition) {
      console.log(`跳过分组 ${getElementIdentifier(groupContainer)}，因为它在第一个组外标签组之后`);
      continue;
    }

    const groupTitle = findTitle(groupContainer) || `标题${index + 1}`;
    const reason = initialReasons[index];
    
    // 为每个分组创建新的标签页管理器
    const groupTabManager = new TabManager();
    const hasTabs = await groupTabManager.initialize();
    
    if (hasTabs) {
      console.log(`处理分组 ${getElementIdentifier(groupContainer)} 的组内标签`);
      // 处理组内标签页
      const innerGroups = await processInnerTabs(groupTabManager, groupContainer, groupTitle, null, extractCards);
      
      if (innerGroups.length > 0) {
        console.log(`在分组 ${getElementIdentifier(groupContainer)} 中找到 ${innerGroups.length} 个组内标签分组`);
        groups.push(...innerGroups);
      } else {
        // 如果没有组内标签，使用原有的提取逻辑
        const cards = extractCards(groupContainer);
        groups.push({
          groupTitle,
          cards: cards || [],
          identifier: getElementIdentifier(groupContainer)
        });
        console.log(`成功提取分组: ${getElementIdentifier(groupContainer)}, 包含 ${cards.length} 个卡片`);
      }
    } else {
      // 如果没有标签页，使用原有的提取逻辑
      const cards = extractCards(groupContainer);
      groups.push({
        groupTitle,
        cards: cards || [],
        identifier: getElementIdentifier(groupContainer)
      });
      console.log(`成功提取分组: ${getElementIdentifier(groupContainer)}, 包含 ${cards.length} 个卡片`);
    }
  }

  return groups;
}

// 处理组内标签页
async function processInnerTabs(tabManager, groupContainer, groupTitle, outerTabName, extractCards) {
  console.log('处理组内标签页:', outerTabName, getElementIdentifier(groupContainer));
  const groups = [];
  let groupIndex = 1;

  // 设置当前容器
  tabManager.setCurrentContainer(groupContainer);
  
  // 获取容器内的标签组
  const innerTabGroups = tabManager.getContainerTabGroups(groupContainer);
  if (innerTabGroups.length === 0) {
    console.log('没有找到标签组，跳过处理');
    return groups;
  }

  // 处理每个标签组
  for (const tabGroup of innerTabGroups) {
    console.log('处理标签组:', getElementIdentifier(tabGroup.element));
    // 重置标签页管理器状态
    tabManager.reset();
    tabManager.currentGroupIndex = tabGroup.groupIndex;
    
    // 处理该标签组的所有标签
    while (true) {
      const result = await tabManager.processCurrentTab(async (tab) => {
        // 提取当前标签下的卡片
        const cards = extractCards(groupContainer, tab.element);
        
        // 检查组名是否与标签页第一项重名
        const isFirstTab = tab.tabIndex === 0;
        const isGroupTitleMatchTab = groupTitle === tab.name;
        
        let finalGroupTitle;
        if (isFirstTab && isGroupTitleMatchTab) {
          // 如果组名与第一个标签页重名，直接使用标签页名称
          finalGroupTitle = outerTabName 
            ? `${outerTabName} - ${tab.name}`
            : tab.name;
        } else {
          // 正常情况下的组名生成
          finalGroupTitle = outerTabName 
            ? `${outerTabName} - ${groupTitle} - ${tab.name}`
            : `${groupTitle} - ${tab.name}`;
        }
        
        return {
          groupTitle: finalGroupTitle,
          cards: cards || [],
          identifier: `${getElementIdentifier(groupContainer)}-tab-${tab.tabIndex}`
        };
      });

      if (result) {
        groups.push(result);
        groupIndex++;
      }

      // 移动到下一个标签
      const hasNext = await tabManager.moveToNextTab();
      if (!hasNext) break;
    }
  }

  return groups;
}

// 处理组外标签页
async function processOuterTabs(tabManager, root, extractCards) {
  const groups = [];
  let groupIndex = 1;

  // 获取容器外的标签组
  const outerTabGroups = tabManager.getOuterTabGroups();
  if (outerTabGroups.length === 0) return groups;

  console.log('找到组外标签组:', outerTabGroups.map(g => getElementIdentifier(g.element)));

  // 处理每个标签组
  for (const tabGroup of outerTabGroups) {
    console.log('处理组外标签组:', getElementIdentifier(tabGroup.element));
    // 不再reset，也不再用currentTabIndex
    for (let tabIndex = 0; tabIndex < tabGroup.options.length; tabIndex++) {
      // 滚动、点击标签
      await tabManager.scrollToTab(tabGroup.groupIndex);
      await tabManager.clickTab(tabGroup.groupIndex, tabIndex);
      
      // 重新读取标签组
      tabManager.tabGroups = tabManager.findTabGroups();
      console.log('点击后重新读取标签组:', tabManager.tabGroups.map(g => getElementIdentifier(g.element)));
      
      // 重新读取分组容器（从当前标签开始）
      const tabElement = tabManager.getTabElement(tabGroup.groupIndex, tabIndex);
      const { containers } = findAllGroupContainers(root, tabElement);
      tabManager.groupContainers = containers;
      console.log('点击后重新读取分组容器:', tabManager.groupContainers.map(c => getElementIdentifier(c)));
      
      // 构造tab对象
      const tab = {
        groupIndex: tabGroup.groupIndex,
        tabIndex,
        name: tabGroup.options[tabIndex],
        element: tabElement
      };
      console.log('处理组外标签:', `${getElementIdentifier(tabGroup.element)}-tab-${tabIndex}`);
      
      // 查找标签之后的所有分组容器
      const { containers: groupContainers, reasons: groupReasons } = findAllGroupContainers(root, tab.element);
      console.log(`在标签 ${tab.name} 下找到 ${groupContainers.length} 个分组容器:`, 
        groupContainers.map(c => getElementIdentifier(c)));
      
      const tabGroups = [];
      for (const [index, groupContainer] of groupContainers.entries()) {
        const reason = groupReasons[index];
        const groupTitle = findTitle(groupContainer) || `标题${groupIndex}`;
        console.log('处理分组:', getElementIdentifier(groupContainer));
        // 提取当前标签下的卡片
        const cards = extractCards(groupContainer, tab.element);
        // 处理组内标签页，传入组外标签名称
        const innerGroups = await processInnerTabs(tabManager, groupContainer, groupTitle, tab.name, extractCards);
        // 添加当前标签下的分组（如果没有组内标签）
        if (innerGroups.length === 0) {
          // 检查组名是否与标签页名称重名
          const isGroupTitleMatchTab = groupTitle === tab.name;
          tabGroups.push({
            groupTitle: isGroupTitleMatchTab ? tab.name : `${tab.name} - ${groupTitle}`,
            cards: cards || [],
            identifier: `${getElementIdentifier(groupContainer)}-tab-${tabIndex}`
          });
        }
        // 添加组内标签页的分组
        tabGroups.push(...innerGroups);
        groupIndex++;
      }
      if (tabGroups.length > 0) {
        console.log('添加组外标签结果:', tabGroups.map(g => g.identifier));
        groups.push(...tabGroups);
      }
    }
  }
  console.log('组外标签处理完成，共找到', groups.length, '个分组');
  return groups;
}

// 提取分组数据
export async function extractGroups(root, extractCards) {
  console.log('开始提取分组数据...');
  
  // 创建标签页管理器
  const tabManager = new TabManager();
  const hasTabs = await tabManager.initialize();
  
  // 处理初始分组
  const initialGroups = await processInitialGroups(root, extractCards);
  
  // 如果有标签页，处理标签页
  if (hasTabs) {
    console.log('找到标签页，开始处理...');
    const tabGroups = await processOuterTabs(tabManager, root, extractCards);
    console.log(`标签页处理完成，共找到 ${tabGroups.length} 个分组`);
    return [...initialGroups, ...tabGroups];
  }
  
  console.log(`数据提取完成，共找到 ${initialGroups.length} 个分组`);
  return initialGroups;
} 